package plgigiel.behaviour.boid.factory;

import java.lang.reflect.Constructor;

import pl.gigiel.behaviour.IBoid;
import pl.gigiel.behaviour.IBoidFactory;
import pl.gigiel.behaviour.IBoidFeatures;
import pl.gigiel.behaviour.IEnvironment;
import pl.gigiel.behaviour.ISteerManager;
import pl.gigiel.behaviour.exception.BehaviourException;


public class BoidFactory implements IBoidFactory {
	private static IBoidFactory boidFactory;

	private BoidFactory() {
	}

	public static IBoidFactory getInstance() {
		if (boidFactory == null) {
			boidFactory = new BoidFactory();
		}
		return boidFactory;
	}

	@Override
	public <T extends IBoid> IBoid createBoid(Class<T> boidClass, IEnvironment environment, ISteerManager steerManager, IBoidFeatures features) throws BehaviourException {
		IBoid boid = null;
		try {
			boid = create(boidClass);
		} catch (Exception e) {
			throw new BehaviourException(e);
		}
		boid.setEnvironment(environment);
		boid.setSteerManager(steerManager);
		boid.setFeatures(features);
		boid.init();
		environment.add(boid);
		return boid;
	}

	private <T extends IBoid> IBoid create(Class<T> boidClass) throws BehaviourException {
		IBoid boid = null;
		try {
			Constructor<T> constructor = boidClass.getConstructor();
			boid = constructor.newInstance();
		} catch (Exception e) {
			throw new BehaviourException(e);
		}
		return boid;
	}
}
